<script> export default { name: 'erp:car' } </script>
<template>
  <el-container>
  

   <el-container ref="printMain">
    <el-header class="mine-el-header">
      <div class="panel-container">
        <!--列表操作-->
        <div class="left-panel">
          <el-button
            icon="el-icon-plus"
            v-auth="['erp:car:save']"
            type="primary"
            @click="add"
          >新增</el-button>

          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            v-auth="['erp:car:delete']"
            :disabled="selection.length==0"
            @click="batchDel"
          >删除</el-button>
          
          <ma-import
            :auth="['erp:car:import']"
            :upload-api="erpCar.importExcel"
            :download-tpl-api="erpCar.downloadTemplate"
            @success="handleSuccess()"
          />
          
          <el-button icon="el-icon-download" v-auth="['erp:car:export']" @click="exportExcel">导出</el-button>
        </div>
        <div class="right-panel">
          <div class="right-panel-search">

            <el-input v-model="queryParams.number" placeholder="请输入车牌号码" clearable />

            <el-tooltip class="item" effect="dark" content="搜索" placement="top">
              <el-button type="primary" icon="el-icon-search" @click="handlerSearch"></el-button>
            </el-tooltip>

            <el-tooltip class="item" effect="dark" content="清空条件" placement="top">
              <el-button icon="el-icon-refresh" @click="resetSearch"></el-button>
            </el-tooltip>

            <el-button type="text" @click="toggleFilterPanel">
              {{ povpoerShow ? '关闭更多筛选' : '显示更多筛选'}}
              <el-icon><el-icon-arrow-down v-if="povpoerShow" /><el-icon-arrow-up v-else /></el-icon>
            </el-button>
          </div>
        </div>
      </div>
      <!--列表筛选-->
      <el-card class="filter-panel" shadow="never">
        <el-form label-width="80px" :inline="true">
          
          <el-form-item label="品牌型号" prop="brand">
            <el-input v-model="queryParams.brand" placeholder="请输入品牌型号" clearable />
          </el-form-item>
        
          <el-form-item label="驾驶员" prop="user_name">
            <el-input v-model="queryParams.user_name" placeholder="请输入驾驶员" clearable />
          </el-form-item>
        
          <el-form-item label="车身颜色" prop="color">
            <el-input v-model="queryParams.color" placeholder="请输入车身颜色" clearable />
          </el-form-item>
        
          <el-form-item label="行驶里程(公里)" prop="mileage">
            <el-input v-model="queryParams.mileage" placeholder="请输入行驶里程(公里)" clearable />
          </el-form-item>
        
          <el-form-item label="发动机型号" prop="engine">
            <el-input v-model="queryParams.engine" placeholder="请输入发动机型号" clearable />
          </el-form-item>
        
          <el-form-item label="车架号码" prop="frame_number">
            <el-input v-model="queryParams.frame_number" placeholder="请输入车架号码" clearable />
          </el-form-item>
        
          <el-form-item label="生产厂家" prop="factory">
            <el-input v-model="queryParams.factory" placeholder="请输入生产厂家" clearable />
          </el-form-item>
        
          <el-form-item label="出厂日期" prop="factory_at">
            <el-date-picker
              v-model="queryParams.factory_at" placeholder="请选择出厂日期时间"
              type="datetime"  
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        
          <el-form-item label="年检到期" prop="year_at">
            <el-date-picker
              v-model="queryParams.year_at" placeholder="请选择年检到期时间"
              type="datetime"  
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        
          <el-form-item label="保险到期" prop="insurance_at">
            <el-date-picker
              v-model="queryParams.insurance_at" placeholder="请选择保险到期时间"
              type="datetime"  
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        
          <el-form-item label="车辆归属" prop="belong">
            <el-select v-model="queryParams.belong" placeholder="请选择车辆归属" clearable>
              <el-option
                v-for='(item, index) in dictData.erp_car_type'
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        
          <el-form-item label="车辆状态" prop="car_status">
            <el-select v-model="queryParams.car_status" placeholder="请选择车辆状态" clearable>
              <el-option
                v-for='(item, index) in dictData.erp_car_status'
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            	<el-option
            		v-for='(item, index) in dictData.platform_data_status'
            		:key="index"
            		:label="item.label"
            		:value="item.value"
            	/>
            </el-select>
          </el-form-item>
        
          <el-form-item label="排序" prop="sort">
            <el-input v-model="queryParams.sort" placeholder="请输入排序" clearable />
          </el-form-item>
        
          <el-form-item label="创建时间" prop="created_at">
            <el-date-picker
              v-model="queryParams.created_at" placeholder="请选择创建时间时间"
              type="datetimerange"  start-placeholder="起始时间" end-placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        
        </el-form>
      </el-card>
    </el-header>
    <!--表格列表-->
    <el-main class="nopadding">
      <maTable
        ref="table"
        :api="api"
        :showRecycle="true"
        row-key="id"
        :hidePagination="false"
        @selection-change="selectionChange"
        @switch-data="switchData"
        stripe
        remoteSort
        @row-contextmenu="rowContextmenu"
      >
        <el-table-column type="selection" width="50"></el-table-column>
        
          <el-table-column label="车牌号码" prop="number"  />

          <el-table-column label="品牌型号" prop="brand"  />

          <el-table-column label="驾驶员" prop="user_name"  />

           <el-table-column label="车身颜色" prop="color">
             <template #default="scope">
                <el-color-picker v-model="scope.row.color" :predefine="proxy.$CONFIG.COLOR_LIST" @change="updateSingle(scope.row.id,'color',scope.row.color)"/>
             </template>
          </el-table-column>

          <el-table-column label="行驶里程(公里)" prop="mileage"  />

          <el-table-column label="发动机型号" prop="engine"  />

          <el-table-column label="车架号码" prop="frame_number"  />

          <el-table-column label="生产厂家" prop="factory"  />

          <el-table-column label="出厂日期" prop="factory_at" width="100"  />

          <el-table-column label="年检到期" prop="year_at" width="100"  />

          <el-table-column label="保险到期" prop="insurance_at" width="100"  />

          <el-table-column label="排放等级" prop="level"  />

          <el-table-column label="车辆归属" prop="belong" >
            <template #default="scope">
              <ma-dict-tag :options="dictData.erp_car_type" :value="scope.row.belong" />
            </template>
          </el-table-column>

          <el-table-column label="车辆价格" prop="peice"  />

          <el-table-column label="车辆状态" prop="car_status" >
            <template #default="scope">
              <ma-dict-tag :options="dictData.erp_car_status" :value="scope.row.car_status" />
            </template>
          </el-table-column>

          <el-table-column label="状态" prop="status" >
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                :active-value="proxy.$CONFIG.SWITCH.ENABLE"
                :inactive-value="proxy.$CONFIG.SWITCH.DISABLE"
                @change="updateSingle(scope.row.id,'status',scope.row.status)"
              />
            </template>
          </el-table-column>

          <el-table-column label="排序" prop="sort"  />

          <el-table-column label="创建时间" prop="created_at" width="100"  />

        <!-- 正常数据操作按钮 -->
        <el-table-column label="操作" fixed="right" align="right" width="130" v-if="!isRecycle">
          <template #default="scope">

            <el-button
              type="text"
              @click="tableEdit(scope.row, scope.$index)"
              v-auth="['erp:car:update']"
            >编辑</el-button>

            <el-button
              type="text"
              @click="deletes(scope.row.id)"
              v-auth="['erp:car:delete']"
            >删除</el-button>

          </template>
        </el-table-column>

        <!-- 回收站操作按钮 -->
        <el-table-column label="操作" fixed="right" align="right" width="130" v-else>
          <template #default="scope">

            <el-button
              type="text"
              v-auth="['erp:car:recovery']"
              @click="recovery(scope.row.id)"
            >恢复</el-button>

            <el-button
              type="text"
              v-auth="['erp:car:realDelete']"
              @click="deletes(scope.row.id)"
            >删除</el-button>

          </template>
        </el-table-column>

      </maTable>
    </el-main>

    <sc-contextmenu ref="contextmenu"  @command="handleCommand" @visible-change="visibleChange">
    	<sc-contextmenu-item command="edit" title="编辑"  suffix="Alt+←" icon="el-icon-edit"></sc-contextmenu-item>
    	<sc-contextmenu-item command="delete" title="删除" suffix="Ctrl+R" icon="el-icon-delete"></sc-contextmenu-item>
    </sc-contextmenu>

   </el-container>
  </el-container>

  <!--操作页面-->
  <save-dialog v-if="dialog.save" ref="saveRef" @success="handleSuccess" @closed="dialog.save=false" />

</template>
<script setup>
  import { ref, reactive, onMounted, nextTick,getCurrentInstance } from 'vue'
  import { useRouter } from 'vue-router'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import erpCar from '@/api/apis/erp/erpCar'
  import tool from '@/utils/tool'
  import systemDict from '@/api/apis/system/dataDict'
  import scContextmenu from '@/components/scContextmenu'
  import scContextmenuItem from '@/components/scContextmenu/item'
  import saveDialog from './save.vue'

  const router = useRouter();
  const { proxy } = getCurrentInstance();
  const table = ref(null)
  const saveRef = ref(null)
  const povpoerShow = ref(false)
  const isRecycle = ref(false)
  const dateRange = ref()
  const selection = ref([])
  const default_tabs_key = ref('-1')
  const contextmenu = ref(null)
  const rowdata = reactive({row:{}})

  const dialog = reactive({ save: false })
  const api = reactive({ list: erpCar.getList, recycleList: erpCar.getRecycleList })
  const queryParams = reactive({
    number: '',
    brand: '',
    user_name: '',
    color: '',
    mileage: '',
    engine: '',
    frame_number: '',
    factory: '',
    factory_at: '',
    year_at: '',
    insurance_at: '',
    belong: '',
    car_status: '',
    status: '',
    sort: '',
    created_at: '',
    
  })
  const dictData = reactive({
    erp_car_type: [],
    erp_car_status: [],
    platform_data_status: [],
    
  })

  onMounted(async () => {
    await getDictData()
  })

  //添加
  const add = async () => {
    dialog.save = true
    await nextTick()
    saveRef.value.open()
  }

   // 标签页查询
    const handleTabsClick = (name) => {
        
    }

  //编辑
  const tableEdit = async (row) => {
    dialog.save = true
    await nextTick()
    saveRef.value.open('edit')
    saveRef.value.setData(row)
  }

  //查看
  const tableShow = async (row) => {
    dialog.save = true
    await nextTick()
    saveRef.value.open('show')
    saveRef.value.setData(row)
  }

  //批量删除
  const batchDel = async () =>{
    await ElMessageBox.confirm(`确定删除选中的 ${selection.value.length} 项吗？`, '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    }).then(async () => {
      let ids = []
      selection.value.map(item => ids.push(item.id))
      let res = isRecycle.value ? await erpCar.realDeletes(ids.join(',')) : await erpCar.deletes(ids.join(','))
      table.value.upData(queryParams)
      ElMessage.success(res.message)
    }).catch(()=>{})
  }

  // 单个删除
  const deletes = async (id) => {
    await ElMessageBox.confirm(`确定删除该数据吗？`, '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    }).then(async () => {
      let res = isRecycle.value ? await erpCar.realDeletes(id) : await erpCar.deletes(id)
      table.value.upData(queryParams)
      ElMessage.success(res.message)
    }).catch(()=>{})
  }

  // 恢复数据
  const recovery = (id) => {
    erpCar.recoverys(id).then(res => {
      ElMessage.success(res.message)
      table.value.upData(queryParams)
    })
  }

  // 右键菜单
  const rowContextmenu = (row,column,event) => {

  	rowdata.row = row
  	table.value.setCurrentRow(row);
  	contextmenu.value.openMenu(event)
  }

  const handleCommand = (command) => {
  	if (command == 'edit') {
  		tableEdit(rowdata.row)
  	}
  	if (command == 'delete') {
  		deletes(rowdata.row.id)
  	}
  }

  const visibleChange = (visible) => {
  	if (!visible) {
  	}
  }

  //表格选择后回调事件
  const selectionChange = (items) => {
    selection.value = items
  }

  const toggleFilterPanel = () => {
    povpoerShow.value = ! povpoerShow.value
    document.querySelector('.filter-panel').style.display = povpoerShow.value ? 'block' : 'none'
  }

  //搜索
  const handlerSearch = () => {
    table.value.upData(queryParams)
  }

  // 切换数据类型回调
  const switchData = () => {
    isRecycle.value = ! isRecycle.value
  }

  // 重置搜索
  const resetSearch = () => {
    for (let k in queryParams) {
        
        queryParams[k] = undefined
    }
    table.value.upData(queryParams)
  }

  // 更新
  const handleSuccess = () =>{
    table.value.upData(queryParams)
  }

  // 获取字典数据
  const getDictData = () => {
    systemDict.getDict('erp_car_type').then(res => {
      dictData.erp_car_type = res.data
    })
    systemDict.getDict('erp_car_status').then(res => {
      dictData.erp_car_status = res.data
    })
    systemDict.getDict('platform_data_status').then(res => {
      dictData.platform_data_status = res.data
    })
    
  }

  // 修改单个数据
  	 const updateSingle = (id, editField,editValue) => {
       	let data = {[editField]: editValue};
       	erpCar.updateSingle(id, data).then(() => {
       		ElMessage.success('修改成功')
       	})
       }

  
  const exportExcel = () => {
    ElMessage.info('正在处理数据...')
    erpCar.exportExcel(queryParams).then( res => {
      tool.download(res)
    }).catch( e => { console.log(e) } )
  }
  
  const numberOperation = (newValue, id, numberName) => {
    erpCar.numberOperation({ id, numberName, numberValue: newValue }).then( res => {
      res.success && ElMessage.success(res.message)
    }).catch( e => { console.log(e) } )
  }
  
  const switchStatus = (statusValue, id, statusName) => {
    erpCar.changeStatus({ id, statusName, statusValue }).then( res => {
      res.success && ElMessage.success(res.message)
    }).catch( e => { console.log(e) } )
  }

</script>